#include "huaqimovie.h"
#include <QDebug>
#include <QPixmap>
#include <QBitmap>
#include <QDir>

#include "common.h"

HuaqiMovie::HuaqiMovie(QWidget *parent) : QObject(parent)
{
    renderLabel = NULL;
    frame_index = 0;
    loop_count = 0;
    frame_interval = 500;
    connect(&timer, SIGNAL(timeout()), this, SLOT(on_timer()));
}

void HuaqiMovie::showOne()
{
    if (imageList.size() == 0)
        return;

    QPixmap pixmap(folder_path + "/" + imageList.at(0));
    renderLabel->setPixmap(pixmap);
}

void HuaqiMovie::start()
{
    timer.start(frame_interval);
}

void HuaqiMovie::stop()
{
    timer.stop();
    frame_index = 0;
}

void HuaqiMovie::setLabel(QLabel* label)
{
    renderLabel = label;
}

void HuaqiMovie::setFileName(QString filename_fl)
{
    char buff1[100] = {0};
    char buff2[100] = {0};
    folder_path = filename_fl;
    FILE * fp = fopen((filename_fl+"/index.txt").toStdString().c_str(), "rb");
    if (fp)
    {
        char *str1 = fgets(buff1, sizeof(buff1), fp);
        char *str2 = fgets(buff2, sizeof(buff2), fp);

        if (str1 && str2)
        {
            //第一行默认新老版本都是帧间隔
            frame_interval = atoi(buff1);

            //第二行如果是1.png那就不解析，老版本的hqv，第二行如果是数字那就是解析成loop_count
            if (!strstr(buff2, ".png"))
                loop_count = atoi(buff2);
        }

        if (str1 && !str2)
        {
            frame_interval = atoi(buff1);
        }

        fclose(fp);
    }
    else
    {
        LOG_QDEBUG << "Hqv open config file fail";
    }

    imageList.clear();
    QDir dir(filename_fl);
    dir.setFilter(QDir::Files | QDir::Hidden | QDir::NoSymLinks | QDir::Dirs | QDir::NoDotAndDotDot);
    dir.setSorting(QDir::Unsorted);
    QFileInfoList fileInfoList = dir.entryInfoList();
    foreach (QFileInfo fileInfo, fileInfoList)
    {
        if (!fileInfo.isDir() && fileInfo.fileName().contains(".png"))
            imageList.push_back(fileInfo.fileName());
    }
}

void HuaqiMovie::on_timer()
{
    frame_index = (frame_index + 1) % imageList.size();

    if (renderLabel)
    {
        QPixmap pixmap(folder_path + "/" + imageList.at(frame_index));
        renderLabel->setPixmap(pixmap);
    }

    //跑到最后一帧，且循环次数等于0，那就关闭定时器了
    if (frame_index == imageList.size() - 1)
    {
        if (--loop_count == 0)
            this->stop();
    }
}

int HuaqiMovie::frameCount()
{
    return imageList.size();
}

QStringList HuaqiMovie::getImageList()
{
    return imageList;
}
